package net.roobook.auth.configure;

import net.roobook.auth.properties.RoobookAuthProperties;
import net.roobook.common.handler.RoobookAccessDeniedHandler;
import net.roobook.common.handler.RoobookAuthExceptionEntryPoint;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.access.AccessDeniedHandler;

/**
 * @Author Roobook
 * @description 资源服务器,处理非/oauth/开头的请求
 * @date 2022/4/7
 */
@Configuration
@EnableResourceServer   // 开启资源服务器相关配置
public class RoobookResourceServerConfigure extends ResourceServerConfigurerAdapter {

    @Autowired
    private RoobookAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private RoobookAuthExceptionEntryPoint exceptionEntryPoint;
    @Autowired
    private RoobookAuthProperties properties;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        String[] anonUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ",");

        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(anonUrls).permitAll()
                //将/actuator/**资源纳入到免认证路径中
                .and()
                .authorizeRequests().antMatchers("/actuator/**").permitAll()
                .antMatchers("/**").authenticated()
                .and().httpBasic();
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(exceptionEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }
}
